# -*-coding:utf-8 -*-
from django.contrib.auth import authenticate
from django.utils.deprecation import MiddlewareMixin
from django.contrib import auth

class TokenAuthenticationMiddleware(MiddlewareMixin):

    def process_request(self, request):
        print '--------------'
        for k,v in request.META.items():
            print k," : ",v
        print '--------------'
        try:
            token = request.META['HTTP_AUTHORIZATION']
            if token.startswith('Token'):
                token = token.replace('Token ', '')
            else:
                return None
        except:
            return None
        user = authenticate(token=token)
        if not user:
            return None
        else:
            request.user = user
            auth.update_session_auth_hash(request, user)
